package com.osi.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osi.bean.Logininfo;
import com.osi.bean.Student;
import com.osi.response.R;
import com.osi.mapper.StudentMapper;
import com.osi.service.StudentService;
import com.osi.utils.UserContext;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lixin
 * @date 2021/2/8 16:13
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Override
    public List<Student> queryList(Student student) {
        return baseMapper.selectList(new QueryWrapper<Student>()
                .eq(StrUtil.isNotEmpty(student.getUsername()), "username", student.getUsername())
                .like(StrUtil.isNotEmpty(student.getName()),"name", student.getName())
        );
    }

    /**
     * 学生登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public Student login(String username, String password) {
        Student student = baseMapper.selectOne(new QueryWrapper<Student>()
                .eq("username", username)
                .eq("password", password)
                .eq("status", 1)
        );

        return student;
    }


    /**
     * 获取当前登录学生信息
     * @return
     */
    @Override
    public Student getOnlineStudent() {
        Logininfo logininfo = UserContext.getCurreentUser();
        Student student = this.getOne(new QueryWrapper<Student>()
                .eq("username", logininfo.getUsername()));
        return student;
    }


    @Override
    public R register(Student student) {

        if (this.selectStudentByUsername(student.getUsername()) != null) {
            // 用户名已存在
            return R.error(400, "用户名已存在");
        }
        int insert = baseMapper.insert(student);
        return R.ok();
    }

    /**
     * 根据用户名查询学生
     *
     * @param username
     * @return
     */
    @Override
    public Student selectStudentByUsername(String username) {
        Student student = baseMapper.selectOne(new QueryWrapper<Student>()
                .eq("username", username)
        );
        return student;
    }


}
